package com.itzhoun.util;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @author 周楠
 * @Date 2022/07/14/下午 10:35
 */
@Component
public class MailTemplate {

    @Resource
    private JavaMailSender javaMailSender;


    public void sendSimpleMail(String from,String to,String cc,String subject,String content){
        //5个参数分别代表的意思是发送者、收件人、抄送人、邮件主题、邮件内容
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setCc(cc);
        message.setSubject(subject);
        message.setText(content);
        javaMailSender.send(message);
    }

    /**
     * MimeMessageHelper简化了配置开发、它的构造方法的第二个参数true表示开启multipart message类型的邮件  可以加附件
     * @param from
     * @param to
     * @param cc
     * @param content
     * @param file
     */
    public void sendAttachFileMail(String from, String to,String cc,String subject, String content, File file){
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setCc(cc);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(content);
            mimeMessageHelper.addAttachment(file.getName(), file);
            javaMailSender.send(mimeMessage);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
